#include "fflib.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include <fstream>

std::ofstream out = std::ofstream();

int readCallback(void* ptr, unsigned char* buf, int size) {
    return 0;
}

int writeCallback(void* ptr, const unsigned char* buf, int size) {
    if (out.is_open() == true) {
        out.write((const char*)buf, size);
    }
    return size;
}

int64_t seekCallBack(void* ptr, int64_t pos, int whence) {
    if (out.is_open() == true) {
        if (whence == 0) {
            out.seekp(pos, std::ios::beg);
        }
    }
    return pos;
}

int closeCallBack(void* ptr) {
    if (out.is_open() == true) {
        out.close();
    }
    return 0;
}

int main(int argc, char** argv) {

    int mempos = -1;
    for (auto i = 0; i < argc; i++) {
        if (strcmp(argv[i], "-mem") == 0) {
            mempos = i;
            break;
        }
    }

    if (mempos == -1) {
        return ffmain(argc, argv);
    }

    char argmem[128] = { 0 };
#ifdef WIN32
    _snprintf(argmem, 127, "mem:%I64x,%I64x,%I64x,%I64x,%I64x.mp4", (uint64_t)readCallback, (uint64_t)writeCallback, (uint64_t)seekCallBack, (uint64_t)closeCallBack, 0);
#else
    snprintf(argmem, 127, "mem:%llx,%llx,%llx,%llx,%llx.mp4", (uint64_t)readCallback, (uint64_t)writeCallback, (uint64_t)seekCallBack, (uint64_t)closeCallBack, 0);
#endif
    for (auto i = 0; i < argc; i++) {
        if (i != mempos) {
            argv[i] = argv[i];
        } else {
            argv[i] = argmem;
        }
    }

    out.open("test.mp4", std::ios::binary | std::ios::out);

    ffmain(argc, argv);
    return 0;
}